<?php
class MapperArtiles
{ 
	private $article;
	public function __construct() {
		mysql_connect(HOST, LOGIN, PASS) or die ('No connect with database');
		mysql_query('SET NAMES utf8');
		mysql_select_db(DB) or die ("error");
	}
	function __destruct() {
		mysql_close();
	}

	public function getAllArticles(/*передавать параметр для сортировки limit*/)
    {
		$query = "SELECT * FROM articles JOIN users ON articles.id_user = users.id_user";
		$r = mysql_query($query) or die(mysql_error());
		$n = mysql_num_rows($r);
		$articles = array();
		for ($i = 0; $i < $n; $i++) {
			$row = mysql_fetch_assoc($r);
			$article = new ModelArticles($row);
			$articles[] = $article;
		}
		return $articles;
	}

	public function getOneArticle($id)
    {
		$id = Validator::validatorIdSql($id);
		$query = "SELECT * FROM articles JOIN users ON articles.id_user = users.id_user WHERE id_article = {$id}";
		$r = mysql_query($query) or die(mysql_error());
		$n = mysql_num_rows($r);
		if ($n != 0) { 
			$row = mysql_fetch_assoc($r);
			$article = new ModelArticles($row);
			return $article;
		} else {
			return null;
		}
	}
	public function createArticle($id_autor, $title, $text, $tags, $video = null) {
		$tags     = Validator::validatorXss($tags);
		$tags     = Validator::validatorSql($tags);
		$text     = Validator::validatorXss($text);
		$text     = Validator::validatorSql($text);
		$title    = Validator::validatorXss($title);
		$title    = Validator::validatorSql($title);
		$id_autor = Validator::validatorIdSql($id_autor);
		if (!empty($video)) {
			$video = Validator::validatorSql($video);
			$video = Validator::validatorVideo($video);
		}
		$query = "INSERT INTO articles (id_user, title, text, video) VALUES ({$id_autor}, '{$title}', '{$text}', '{$video}')";
		$r = mysql_query($query) or die(mysql_error());
		$idArticle = mysql_insert_id();
		if ($r) {
			if (!empty($tags)) {
				$this->createTags($idArticle, $tags);
			}
			return $idArticle;
		} else {
			return false;
		}
	}
	public function addTags($idArticle, $thereTagsId) {
		$findTag = "SELECT `id_tag` FROM `tags` WHERE `id_tag` = {$thereTagsId} ";
		$resultTag = mysql_query($findTag) or die(mysql_error());
		$findLink = "SELECT * FROM `articles_tags` WHERE `id_article` = {$idArticle} AND id_tag = {$thereTagsId}";
		$resultLink = mysql_query($findLink) or die(mysql_error());
		$numLink = mysql_num_rows($resultLink);	
		if (empty($numLink)) {
			$createLink = "INSERT INTO articles_tags (id_article, id_tag) VALUES ({$idArticle}, {$thereTagsId})";
			$resultCreateLink = mysql_query($createLink) or die(mysql_error());
			$queryUpdate = "UPDATE  `tags` SET `count` = (`count` + 1) WHERE  `id_tag` = {$thereTagsId}";
			$result = mysql_query($queryUpdate) or die(mysql_error());
		}
		return true;
	}
	public function createTags($idArticle, $tags) {
		$arrTags = explode(",", $tags);
		if (!empty($arrTags)) {
			for ($i = 0; $i < count($arrTags); $i++) {
				$arrTags[$i] = Validator::validatorXss($arrTags[$i]);
				$arrTags[$i] = Validator::validatorSql($arrTags[$i]);
				$arrTags[$i] = trim(mb_strtolower($arrTags[$i], 'UTF-8'));
				$findTag = "SELECT `id_tag` FROM `tags` WHERE `title` = '{$arrTags[$i]}'";
				$resultTag = mysql_query($findTag) or die(mysql_error());
				$numTag = mysql_num_rows($resultTag);
				if (!empty($numTag)) {
					$idTag = mysql_fetch_assoc($resultTag);
					$findLink = "SELECT * FROM `articles_tags` WHERE `id_article` = {$idArticle} AND id_tag = {$idTag['id_tag']}";
					$resultLink = mysql_query($findLink) or die(mysql_error());
					$numLink = mysql_num_rows($resultLink);	
					if (empty($numLink)) {
						$createLink = "INSERT INTO articles_tags (id_article, id_tag) VALUES ({$idArticle}, {$idTag['id_tag']})";
						$resultCreateLink = mysql_query($createLink) or die(mysql_error());
						$queryUpdate = "UPDATE  `tags` SET `count` = (`count` + 1) WHERE  `id_tag` = {$idTag['id_tag']}";
						$result = mysql_query($queryUpdate) or die(mysql_error());
					} 
				} else {
					$count = intval(1);
					$queryInsertTag = "INSERT INTO tags (title, count) VALUES ('{$arrTags[$i]}', {$count} )";
					$resultInsertTag = mysql_query($queryInsertTag) or die(mysql_error());
					$idTag = mysql_insert_id();
					$insertLink = "INSERT INTO articles_tags (id_article, id_tag) VALUES ({$idArticle}, {$idTag})"; 
					$resultInsertLink = mysql_query($insertLink) or die(mysql_error());
				}			
			}	
			return true;
		} else {
			return false;
		}
	}
	public function editArticle($id, $title, $text, $tags) {
		$title = Validator::validatorXss($title);
		$title = Validator::validatorSql($title);
		$text  = Validator::validatorXss($text);
		$text  = Validator::validatorSql($text);
		$tags  = Validator::validatorXss($tags);
		$tags  = Validator::validatorSql($tags);
		$id    = Validator::validatorIdSql($id);
		$query = "UPDATE  `articles` SET  `text` = '{$text}', `title` = '{$title}'   WHERE  `id_article` ={$id}";
		$this->createTags($id, $tags);
		$r = mysql_query($query) or die(mysql_error());
		return true;
	}
	public function delArticle($id) {
		$id   = Validator::validatorIdSql($id);
		$query = "DELETE FROM `articles` WHERE `id_article` = {$id}";
		$r = mysql_query($query) or die(mysql_error());
		if ($r) {
			return true;
		} else {
			return false;
		}
	}

    /**
     * @param $idAutor
     * @return array
     */
    public function getSortArticlesByAutor($idAutor) {
		$idAutor = Validator::validatorIdSql($idAutor);
		$query = "SELECT * FROM articles JOIN users ON articles.id_user = users.id_user WHERE users.id_user = {$idAutor}";
		$r = mysql_query($query) or die(mysql_error());
		$n = mysql_num_rows($r);
		$articles = array();
		for ($i = 0; $i < $n; $i++) {
			$row = mysql_fetch_assoc($r);
			$article = new ModelArticles($row);
			$articles[] = $article;
		}
		return $articles;
	}
	public function getSortArticlesByTags($idTag) {
		$idTag = Validator::validatorIdSql($idTag);
		$query = "SELECT * FROM articles JOIN articles_tags ON articles.id_article = articles_tags.id_article "
			   . "JOIN users ON articles.id_user = users.id_user WHERE articles_tags.id_tag = {$idTag}";
		$r = mysql_query($query) or die(mysql_error());
		$n = mysql_num_rows($r);
		$articles = array();
		for ($i = 0; $i < $n; $i++) {
			$row = mysql_fetch_assoc($r);
			$article = new ModelArticles($row);
			$articles[] = $article;
		}
		return $articles;
	}
}
